var util = require('../../utils/util.js');
Page( {
  data: {
    user: {}
  },

  onLoad: function() {
    var user = wx.getStorageSync('user');
    this.setData({ user: user });
  },

  // 点击进入选择/新增地址
  editAddress: function () {
    wx.chooseAddress({
      success: res => {
        this.saveAddress(res);
      },
      fail: function (res) {
        console.log('fail', res);
      }
    });
  },

  saveAddress: function (formData) {
    console.log('formData', formData);
    if (formData.provinceName.indexOf('新疆') > -1
     || formData.provinceName.indexOf('西藏') > -1
     || formData.provinceName.indexOf('内蒙古') > -1) {
      wx.showModal({ content: '抱歉，暂不支持该地址配送！', showCancel: false });
      return;
    }
    var data = {
      "uid": "o_uEm0XlBxSFNxpKBK0v_og1dj0Y",
      "phone": formData.telNumber,
      "name": formData.userName,
      "address": formData.provinceName + formData.cityName + formData.countyName + formData.detailInfo,
      "flag": 1
    }
    wx.request({
      url: util.requestUrl.addressSave,
      method: 'POST',
      data: data,
      header: { 'content-type': 'application/json' },
      success: function (res) {
        console.log('res', res);
        if (res.data.success) {
          console.log('保存地址成功！');
        }
      }
    });
  },

   // 用户授权头像信息
   oauthUserInfo: function () {
    var user = this.data.user;
    if (user == null || user.avatarUrl != null) return;

    wx.getUserProfile({
      lang: 'zh_CN',
      desc: '用于显示用户头像',
      success: (res) => {
        console.log('getUserProfile()', res);
        var userInfo = res.userInfo;
        
        user['nickName'] = userInfo.nickName;
        user['avatarUrl'] = userInfo.avatarUrl;
        this.setData({ user: user });

        // 修改信息
        wx.request({
          url: util.requestUrl.updateUser,
          method: 'POST',
          header: { 'content-type': 'application/json' },
          data: {
            id: user.id,
            uid: user.uid,
            nickName: user.nickName,
            avatarUrl: user.avatarUrl
          },
          success: function (res) {
            console.log('updateUserInfo', res);
          }
        });
      },
      complete: res => {
        console.log('getUserProfile:complete', res);
        if (res.errMsg == 'getUserProfile:fail auth deny') {
          wx.showToast({ title: '为了更好的使用体验，建议你同意授权哦！', icon: 'none' });
        }
      }
    });
  },

  addAddress: function () {
    wx.navigateTo({ url: '/pages/address/address' });
  },

})
